package com.shop.trade.api.controller;

import com.shop.common.model.InputBean;
import com.shop.common.model.ServiceBean;
import com.shop.common.model.param.trade.ShoppingCartInput;
import com.shop.common.model.result.trade.ShoppingCartOutput;
import com.shop.common.tmpl.BaseController;
import com.shop.common.util.SessionUtils;
import com.shop.common.util.excption.UserNotFoundException;
import com.shop.trade.api.api.IShopCartApi;
import com.shop.trade.api.service.IShopCartSvc;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @Description:
 *
 * @author zhoulk
 * @date: 2019年04月05日  16:52
 */
@RestController
public class ShopCartController extends BaseController implements IShopCartApi {
    @Autowired
    SessionUtils sessionUtils;
    @Autowired
    IShopCartSvc iShopCartSvc;

    @Override
    public String addToShopCart(@RequestBody ShoppingCartInput shoppingCartInput, HttpServletRequest request) throws UserNotFoundException {
        Integer userId = sessionUtils.USER_ID(request);
        shoppingCartInput.setUserId(userId);
        return returnSvc(iShopCartSvc.addToShopCart(shoppingCartInput));
    }

    @Override
    public String modShopCartNum(@RequestBody ShoppingCartInput shoppingCartInput, HttpServletRequest request) {
        return returnSvc(iShopCartSvc.modShopCartItemNum(shoppingCartInput));
    }


    @Override
    public String delShopCart(String id, HttpServletRequest request) {
        String[] ids = id.split("^");
        List<Integer> idList = new ArrayList<>();
        for (String idt : ids) {
            idList.add(Integer.valueOf(idt));
        }
        return returnSvc(iShopCartSvc.delShopCart(idList));
    }

    @Override
    public String qryShopCarts(ShoppingCartInput shoppingCartInput, String size, HttpServletRequest request) throws UserNotFoundException {
        Integer userId = sessionUtils.USER_ID(request);
        shoppingCartInput.setUserId(userId);
        InputBean<ShoppingCartInput> inputBean = new InputBean<>();
        inputBean.setPageSize(Integer.valueOf(size));
        inputBean.setIndex(1);
        inputBean.setParam(shoppingCartInput);
        ServiceBean<Map<Integer, List<ShoppingCartOutput>>> serviceBean = iShopCartSvc.qryShoppingCarts4P(inputBean);
        Map<Integer, List<ShoppingCartOutput>> map = serviceBean.getData();
        if (map == null || map.isEmpty()) {
            return returnFailed();
        }
        List<List<ShoppingCartOutput>> lists = new ArrayList<>();
        Set<Integer> keys = map.keySet();
        for (Integer key : keys) {
            lists.add(map.get(key));
        }
        return returnData(lists);
    }
}
